#!/usr/bin/env groovy
package com.yidao.www

def autoBuild(project, branch, packageType, robot, robotBranch, version, number){

    def date = new Date()
    def upgradeToolsProfile = upgradeToolsProfile(project, branch, packageType)
    def label = upgradeToolsProfile.label.get(packageType)
    def gitUrl = upgradeToolsProfile.gitUrl
    def scriptDir = upgradeToolsProfile.scriptDir.get(packageType)
    def buildScript = upgradeToolsProfile.buildScript.get(packageType)
    def packageScript = upgradeToolsProfile.packageScript.get(packageType)
    def config = upgradeToolsProfile.config.get(packageType)
    def artifact = upgradeToolsProfile.artifact.get(packageType)
    def packageName = upgradeToolsProfile.package.get(packageType)
    def artifactory = upgradeToolsProfile.artifactory
    def base = new base()
    def deployTarget = base.backupFolder(artifactory, project, branch, date)
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url
    def storageURL

    println '============================================== BUILD INFO =============================================='
    println upgradeToolsProfile
    println 'label: ' + label
    println 'gitUrl: ' + gitUrl
    println 'scriptDir: ' + scriptDir
    println 'buildScript: ' + buildScript
    println 'config: ' + config
    println 'artifact: ' + artifact
    println 'packageName: ' + packageName
    println 'artifactory: ' + artifactory
    println 'deployTarget: ' + deployTarget
    println '============================================== BUILD INFO =============================================='

    node(label){

        stage('checkout'){
            storageURL = srverUrl + '/' + deployTarget
            try{
                base.gitClone(gitUrl, branch)
            }catch(e){
                // notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                println '代码克隆失败!'
                println e
                currentBuild.result = 'FAILURE'
                base.influxDb()
                error e.getMessage()
            }
        }

        stage('build'){
            try{
                dir(scriptDir){
                    if(label == 'WINSERVER'){
                        base.batScriptStatus(buildScript)
                    }else{
                        base.scriptStatus(buildScript)
                    }

                }
            }catch(e){
                println '[ERROR] 编译失败!'
                println e
                currentBuild.result = 'FAILURE'
                base.influxDb()
                error e.getMessage()
            }
        }

        if(config){
            def json = base.generateConfigJson(robot, number, version, robotBranch)
            def jsonObj = base.readJson(json)
            def steps = jsonObj.steps
            /*
            只有 beta 版本有 tail
            */
            steps.each{
                if(robotBranch != 'dev-beta' && it.device == 'tail'){
                    steps.remove(it)
                }
            }
            def jsonStr = base.map2JsonStr(jsonObj)
            base.writeFile(jsonStr, config)
            print jsonStr
        }

        stage('package'){
            try{
                if(packageScript){
                    dir(scriptDir){
                        if(label == 'WINSERVER'){
                            base.batScriptStatus(packageScript)
                        }else if(label == 'ANDROID'){
                            return null
                        }else{
                            base.scriptStatus(packageScript)
                        }
                    }
                }else{
                    base.zipPackage(packageName, artifact)
                }
            }catch(e){
                println '[ERROR] 打包失败!'
                println e
                currentBuild.result = 'FAILURE'
                base.influxDb()
                error e.getMessage()
            }
        }

        stage('upload'){
            base.fileUpload(packageName, deployTarget)
        }

        stage('clean'){
            cleanWs()
        }

        stage('retrun artifact'){
            currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
            return deployTarget
        }
    }
}

def autoBuildWithK8s(project, branch, packageType, robot, robotBranch, version, number){

    def date = new Date()
    def upgradeToolsProfile = upgradeToolsProfile(project, branch, packageType)
    def label = upgradeToolsProfile.label.get(packageType) + '_' + BUILD_NUMBER
    def image = upgradeToolsProfile.image.get(packageType)
    def gitUrl = upgradeToolsProfile.gitUrl
    def scriptDir = upgradeToolsProfile.scriptDir.get(packageType)
    def buildScript = upgradeToolsProfile.buildScript.get(packageType)
    def packageScript = upgradeToolsProfile.packageScript.get(packageType)
    def config = upgradeToolsProfile.config.get(packageType)
    def artifact = upgradeToolsProfile.artifact.get(packageType)
    def packageName = upgradeToolsProfile.package.get(packageType)
    def artifactory = upgradeToolsProfile.artifactory
    def base = new base()
    def deployTarget = base.backupFolder(artifactory, project, branch, date)
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url
    def storageURL

    println '============================================== BUILD INFO =============================================='
    println upgradeToolsProfile
    println 'label: ' + label
    println 'image: ' + image
    println 'gitUrl: ' + gitUrl
    println 'scriptDir: ' + scriptDir
    println 'buildScript: ' + buildScript
    println 'config: ' + config
    println 'artifact: ' + artifact
    println 'packageName: ' + packageName
    println 'artifactory: ' + artifactory
    println 'deployTarget: ' + deployTarget
    println '============================================== BUILD INFO =============================================='

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins') {

            node(label){

                stage('checkout'){
                    storageURL = srverUrl + '/' + deployTarget
                    try{
                        base.gitClone(gitUrl, branch)
                    }catch(e){
                        // notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('build'){
                    try{
                        dir(scriptDir){
                            if(label == 'WINSERVER'){
                                base.batScriptStatus(buildScript)
                            }else{
                                base.scriptStatus(buildScript)
                            }

                        }
                    }catch(e){
                        println '[ERROR] 编译失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                if(config){
                    def json = base.generateConfigJson(robot, number, version, robotBranch)
                    def jsonObj = base.readJson(json)
                    def steps = jsonObj.steps
                    /*
                    只有 beta 版本有 tail
                    */
                    steps.each{
                        if(robotBranch != 'dev-beta' && it.device == 'tail'){
                            steps.remove(it)
                        }
                    }
                    def jsonStr = base.map2JsonStr(jsonObj)
                    base.writeFile(jsonStr, config)
                    print jsonStr
                }

                stage('package'){
                    try{
                        if(packageScript){
                            dir(scriptDir){
                                if(label == 'WINSERVER'){
                                    base.batScriptStatus(packageScript)
                                }else if(label == 'ANDROID'){
                                    return null
                                }else{
                                    base.scriptStatus(packageScript)
                                }
                            }
                        }else{
                            base.zipPackage(packageName, artifact)
                        }
                    }catch(e){
                        println '[ERROR] 打包失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('upload'){
                    base.fileUpload(packageName, deployTarget)
                }

                stage('clean'){
                    cleanWs()
                }

                stage('retrun artifact'){
                    currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                    return deployTarget
                }
            }
        }
}